<template>
	<div class="app-container">
		<div ref="box1" class="total-box">
			<div class="total-item">
				<div class="total-title">
					<span>品种数</span>
					<el-popover width="600" trigger="click">
						<jk-table :span-method="spanMethod" :data="totalInfo.productList || []" size="mini" :height="200">
							<vxe-column :min-width="150" field="productName" title="品种"></vxe-column>
							<vxe-column :width="140" field="batchCode" title="批号"></vxe-column>
							<vxe-column :width="100" align="right" field="packNum" title="包数"></vxe-column>
							<vxe-column :width="100" align="right" field="qty" title="重量"></vxe-column>
						</jk-table>
						<span slot="reference" class="el-icon-info"></span>
					</el-popover>
				</div>
				<div class="total-val">{{ totalInfo.productList ? totalInfo.productList.length : 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">包数</div>
				<div class="total-val">{{ totalInfo.allPackNum || 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">重量</div>
				<div class="total-val">{{ totalInfo.allQty || 0 }}</div>
			</div>
			<div class="total-item">
				<div class="total-title">
					<span>异常</span>
					<el-popover width="600" trigger="click">
						<jk-table :span-method="spanMethod" :data="totalInfo.failProductList || []" size="mini" :height="200">
							<vxe-column :min-width="150" field="productName" title="品种"></vxe-column>
							<vxe-column :width="140" field="batchCode" title="批号"></vxe-column>
							<vxe-column :width="100" align="right" field="packNum" title="包数"></vxe-column>
							<vxe-column :width="100" align="right" field="qty" title="重量"></vxe-column>
						</jk-table>
						<span slot="reference" class="el-icon-info"></span>
					</el-popover>
				</div>
				<div class="total-val">{{ totalInfo.failNum || 0 }}</div>
			</div>
		</div>
		<jk-operation-card ref="box2" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<!--<el-popover title="匹配规则(自上而下)" trigger="click">
						<div>
							<div class="margin-bottom-4 width-100-percent"><el-tag class="width-100-percent">1、启用的纸管颜色 + 生产中</el-tag></div>
							<div class="margin-bottom-4 width-100-percent"><el-tag class="width-100-percent">2、品种 + 批号 + 纸管颜色(启用+停用)</el-tag></div>
							<div class="width-100-percent"><el-tag class="width-100-percent">3、品种 + 纸管颜色(启用+停用)</el-tag></div>
						</div>
						<jk-button slot="reference" size="small" icon="el-icon-info"></jk-button>
					</el-popover>-->
					<div><el-button type="warning" class="item-gap" size="small" :loading="exportLoading" @click="onReportBtn">导出</el-button></div>
				</div>
				<div class="flex-end-center-wrap">
					<jk-select v-model="searchParams.workshopId" disabled :option-list="workshopList" placeholder="区域" :clearable="false" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange"></jk-select>
					<jk-date-picker v-model="searchParams.belongDate" placeholder="打包日期" size="small" class="search-bar-item-size2 margin-5-0 item-gap" :clearable="false" @change="onBelongDateChange" />
					<jk-select v-model="searchParams.shiftId" :option-list="shiftList" placeholder="班次" size="small" class="search-bar-item-size1 margin-5-0 item-gap" clearable />
					<jk-select v-model="searchParams.mateState" :option-list="auditStateList" placeholder="状态" clearable size="small" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.pinzhong" placeholder="品种" clearable size="small" class="search-bar-item-size3 margin-5-0 item-gap" @on-enter="onSearchBtn"></jk-search-input>
					<jk-search-input v-model="searchParams.pihao" placeholder="批号" clearable size="small" class="search-bar-item-size2 margin-5-0 item-gap" @on-enter="onSearchBtn"></jk-search-input>
					<!--<jk-select v-model="searchParams.machineNameOrCode" :option-list="machineList" placeholder="打包机" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />-->
					<jk-search-input v-model="searchParams.machineNameOrCode" :option-list="machineList" placeholder="打包机" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table ref="jkTable" :loading="tableLoading" :data="tableData" :height="tableHeight + 10">
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template slot-scope="scope">
						<span v-if="item.keyName === 'shebei'">{{ `${scope.row.shebei}号打包机` }}</span>
						<el-tag v-else-if="item.keyName === 'mateState'" :type="scope.row.mateState ? 'success' : 'danger'" size="mini">{{ scope.row.mateState ? '成功' : '失败' }}</el-tag>
						<!--<jk-state-bar v-else-if="item.keyName === 'mateState'" :state-list="auditStateList" :state="scope.row.mateState"></jk-state-bar>-->
						<div v-else-if="item.keyName === 'paperTubeList'">{{ scope.row.paperTubeList ? scope.row.paperTubeList.map(x => x.name).join(',') : '无' }}</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="100">
					<template slot-scope="scope">
						<div class="flex-center">
							<jk-button size="mini" type="primary" @click="onEditBtn(scope.row)">修正</jk-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box3" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:page-type="pageType"
			:data-item="dataItem"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
	</div>
</template>

<script>
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, formatDate } from '/src/utils/jk/jk-tool';
    import {
        productionLabellingMachineRecordList,
        productionLabellingMachineRecordGetByDate,
        productionLabellingMachineRecordPage
    } from '/src/api/production/package';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import shiftSelect from '../../../jk-components/jk-shift-select';
    import { workforcemanagementShiftPage } from '../../../../api/schedule/shift';
    import saveDialog from './save-dialog';

    export default {
        name: 'PackageRecord',
        components: {
            saveDialog,
            shiftSelect
        },
        mixins: [calHeight, getMenuColumn],
        data() {
            return {
                apiItem: {
                    'page': productionLabellingMachineRecordPage
                },
                workshopList: [],
                pageType: '',
                prefix: '',
                machineList: [
                    { id: 1, name: '1号打包机' },
                    { id: 2, name: '2号打包机' }
                ],
                auditStateList: [
                    { id: true, name: '成功', color: '#19be6b' },
                    { id: false, name: '失败', color: '#ed4014' }
                ],
                dataId: null,
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                shiftList: [],
                totalCount: 0,
                searchParams: {
                    pageNo: pageConfig.pageNo,
                    pageSize: pageConfig.pageSize,
                    pinzhong: '',
                    belongDate: '',
                    machineNameOrCode: '',
                    shiftId: null,
                    pihao: '',
                    auditState: null
                },
                totalInfo: {
                    allPackNum: 0,
                    allQty: 0,
                    failNum: 0,
                    failProductList: [],
                    productList: []
                },
                dataItem: {}
            };
        },
        methods: {
            spanMethod({ row, _rowIndex, column, visibleData }) {
                const prevRow = visibleData[_rowIndex - 1];
                let nextRow = visibleData[_rowIndex + 1];
                if (column.property === 'productName') {
                    if (prevRow && prevRow.productName === row.productName) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow.productName === row.productName) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onWorkshopChange() {
                this.$set(this.searchParams, 'shiftId', null);
                this.shiftList = [];
                this.getShiftListByWorkshopRequest();
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.searchParams ? JSON.parse(JSON.stringify(this.searchParams)) : {};
                params.pageNo = 1;
                params.pageSize = 500;
                this.$modal.confirm('是否确认导出所有数据数据项?').then(() => {
                    this.exportLoading = true;
                }).then(() => {
                    this.exportLoading = false;
                    return productionLabellingMachineRecordList(params).then(res => {
                        if (res.data.status === 200) {
                            import('@/vendor/Export2Excel').then(excel => {
                                const tHeader = this.tableColumnList.map(x => x.title);
                                const filterVal = this.tableColumnList.map(x => x.keyName);
                                const list = res.data.res ? JSON.parse(JSON.stringify(res.data.res)).map(item => {
                                    item.mateState = item.mateState ? '成功' : '失败';
                                    item.paperTubeList = item.paperTubeList.map(x => x.name).join(',');
                                    return item;
                                }) : [];
                                const data = list.map(v => filterVal.map(j => {
                                    return v[j];
                                }));
                                excel.export_json_to_excel({
                                    header: tHeader,
                                    data,
                                    filename: `${this.$route.meta.title}-${this.searchParams.belongDate}`,
                                    autoWidth: true,
                                    bookType: 'xlsx'
                                });
                            });
                        }
                    });
                }).catch(() => {});
            },
            onEditBtn(e) {
                this.dataItem = e;
                this.saveDialogState = true;
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                this.saveDialogState = e;
                if (!e) {
                    this.dataItem = {};
                }
            },
            onBelongDateChange(e) {
                if (e) {
                    this.onSearchBtn();
                } else {
                    this.$set(this.searchParams, 'shiftId', null);
                }
            },
            onSearchBtn() {
                this.$set(this.searchParams, 'pageNo', 1);
                this.getListRequest();
            },
            onPageChange(e, size) {
                this.$set(this.searchParams, 'pageNo', e);
                this.$set(this.searchParams, 'pageSize', size);
                this.getListRequest();
            },
            // 获取区域的班次
            getShiftListByWorkshopRequest() {
                this.shiftList = [];
                if (!this.searchParams.workshopId) return;
                return workforcemanagementShiftPage({
                    workshopId: this.searchParams.workshopId
                }).then(res => {
                    if (res.data.status === 200) {
                        this.shiftList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.tableLoading = true;
                this.workshopList = this.$store.state.user.userWorkshop.workshopList || [];
                const item = this.workshopList.find(x => x.code.toUpperCase() === 'ZL') || {};
                this.$set(this.searchParams, 'workshopId', item.id);
                if (!this.searchParams.belongDate) this.$set(this.searchParams, 'belongDate', formatDate(Date.now()));
                await this.getMenuColumnListRequest();
                await this.getShiftListByWorkshopRequest();
                await this.getListRequest();
                this.tableLoading = false;
            },
            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.getTotalInfoRequest();
                return this.apiItem['page'](this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res || [];
                        this.totalCount = res.data.count;
                    }
                });
            },
            getTotalInfoRequest() {
                return productionLabellingMachineRecordGetByDate(this.searchParams).then(res => {
                    if (res.data.status === 200) {
                        this.totalInfo = res.data.res || {};
                    }
                });
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
<style scoped lang="scss">
    .total-box {
        display: flex;
        justify-content: center;
        align-items: center;
        margin-bottom: 10px;
        .total-item {
            width: 100px;
            height: 70px;
            background: #fff;
            border: solid 1px #eee;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin: 0 5px;
            border-radius: 10px;
            box-shadow: 0 0 2px 1px #eee;
            .total-title {
                color: #808695;
                font-size: 16px;
            }
            .total-val {
                font-size: 18px;
                color: #515a6e;
                margin-top: 2px;
            }
        }
        .total-item:hover {
            box-shadow: 0 0 2px 1px #eee;
        }
    }
</style>
